<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://chenjiabing666.github.io/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="code-ltfpVmGDr3" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Mybatis," />





  <link rel="alternate" href="/atom.xml" title="不才陈某技术博客" type="application/atom+xml" />






<meta name="description" content="前言
通过前两篇的文章我们了解了Mybatis基本的CRUD操作、一些基本标签的属性以及如何映射结果，感兴趣的可以看我的前两篇文章，分别是Mybatis入门之基础操作和Mybatis结果映射，你射准了吗？，如果有什么疑问的地方可以在文章下方留言，作者统一回复。
这篇文章就来聊一聊Mybatis的动态SQL，在实际的开发中Mybatis的这项功能是非常重要的，至于什么是动态SQL？如何实现动态SQL">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis.动态SQL，你真的会了吗？">
<meta property="og:url" content="https://chenjiabing666.github.io/2020/04/20/Mybatis.动态SQL，你真的会了吗？/index.html">
<meta property="og:site_name" content="不才陈某技术博客">
<meta property="og:description" content="前言
通过前两篇的文章我们了解了Mybatis基本的CRUD操作、一些基本标签的属性以及如何映射结果，感兴趣的可以看我的前两篇文章，分别是Mybatis入门之基础操作和Mybatis结果映射，你射准了吗？，如果有什么疑问的地方可以在文章下方留言，作者统一回复。
这篇文章就来聊一聊Mybatis的动态SQL，在实际的开发中Mybatis的这项功能是非常重要的，至于什么是动态SQL？如何实现动态SQL">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E5%8A%A8%E6%80%81SQL/1.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/%E4%B8%83%E7%A7%92%E7%BC%96%E7%A8%8B.jpg">
<meta property="og:updated_time" content="2020-10-23T11:02:17.841Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Mybatis.动态SQL，你真的会了吗？">
<meta name="twitter:description" content="前言
通过前两篇的文章我们了解了Mybatis基本的CRUD操作、一些基本标签的属性以及如何映射结果，感兴趣的可以看我的前两篇文章，分别是Mybatis入门之基础操作和Mybatis结果映射，你射准了吗？，如果有什么疑问的地方可以在文章下方留言，作者统一回复。
这篇文章就来聊一聊Mybatis的动态SQL，在实际的开发中Mybatis的这项功能是非常重要的，至于什么是动态SQL？如何实现动态SQL">
<meta name="twitter:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E5%8A%A8%E6%80%81SQL/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chenjiabing666.github.io/2020/04/20/Mybatis.动态SQL，你真的会了吗？/"/>





  <title>Mybatis.动态SQL，你真的会了吗？ | 不才陈某技术博客</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不才陈某技术博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信公众号：码猿技术专栏</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenjiabing666.github.io/2020/04/20/Mybatis.动态SQL，你真的会了吗？/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="不才陈某">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不才陈某技术博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Mybatis.动态SQL，你真的会了吗？</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-20T17:01:42+08:00">
                2020-04-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Mybatis进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Mybatis进阶</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/04/20/Mybatis.动态SQL，你真的会了吗？/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/04/20/Mybatis.动态SQL，你真的会了吗？/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
		  
		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
			

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><ul>
<li>通过前两篇的文章我们了解了Mybatis基本的CRUD操作、一些基本标签的属性以及如何映射结果，感兴趣的可以看我的前两篇文章，分别是<a href="https://mp.weixin.qq.com/s/KdrEvlShnVoYA8nr0qLSNw" target="_blank" rel="external">Mybatis入门之基础操作</a>和<a href="https://mp.weixin.qq.com/s/czICR6jv1yz6adi6G3xFgQ" target="_blank" rel="external">Mybatis结果映射，你射准了吗？</a>，如果有什么疑问的地方可以在文章下方留言，作者统一回复。</li>
<li>这篇文章就来聊一聊Mybatis的动态SQL，在实际的开发中Mybatis的这项功能是非常重要的，至于什么是动态SQL？如何实现动态SQL？下面文章将会详细介绍。</li>
</ul>
<h2 id="什么是动态SQL？"><a href="#什么是动态SQL？" class="headerlink" title="什么是动态SQL？"></a>什么是动态SQL？</h2><ul>
<li>动态 SQL 是 MyBatis 的强大特性之一。顾名思义，就是会动的SQL，即是能够灵活的根据某种条件拼接出完整的SQL语句。这种类似于MySQL中的<code>case when then else then end....</code>这种语法，能够根据某种条件动态的拼接出需要的SQL。</li>
<li>至于Mybatis如何实现动态SQL呢，Mybatis提供了非常多的标签，能够让我们在XML文件中灵活的运用这些标签达到拼接SQL的目的。</li>
</ul>
<h2 id="常用的标签"><a href="#常用的标签" class="headerlink" title="常用的标签"></a>常用的标签</h2><ul>
<li>Mybatis为了能够让开发者灵活的写SQL也是费了一番功夫，定义了很多的标签和语法，下面将会一一介绍。</li>
</ul>
<h3 id="if"><a href="#if" class="headerlink" title="if"></a>if</h3><ul>
<li>虽然英文不太好，但是在这么简单的不会不知道是<code>如果</code>的意思吧，Java语法中也有，只有判断条件为<code>true</code>才会执行其中的SQL语句。</li>
<li>举个栗子：HIS系统中医护人员需要根据特定条件筛选患者，比如住院号，床位，性别等。当然这些条件并不是必填的，具体的功能截图如下:<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E5%8A%A8%E6%80%81SQL/1.png" alt=""></li>
<li><p>以上截图中的条件筛选并不是必填的，因此我们不能在SQL中固定，要根据前端是否传值来判断是否需要加上这个条件。那么此时查询语句如何写呢？如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span> =<span class="string">'selectPats'</span> <span class="attr">resultType</span>=<span class="string">'com.xxx.domain.PatientInfo'</span>&gt;</span></div><div class="line">  select * from patient_info </div><div class="line">  where status=1</div><div class="line">  <span class="comment">&lt;!--前端传来的住院号不为null，表示需要根据住院号筛选，此时Where语句就需要加上这个条件--&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"iptNum!=null"</span>&gt;</span></div><div class="line">      and ipt_num=#&#123;iptNum&#125;</div><div class="line">  <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">  </div><div class="line">  <span class="comment">&lt;!--床位号筛选--&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"bedNum!=null"</span>&gt;</span></div><div class="line">      and bed_num=#&#123;bedNum&#125;</div><div class="line">  <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p><code>&lt;if&gt;</code>标签中的属性<code>test</code>用来指定判断条件，那么问题来了，上面的例子中的<code>test</code>中判断条件都是一个条件，如果此时变成两个或者多个条件呢？和SQL的语法类似，<code>and</code>连接即可，如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"bedNum!=null and bedNum!='' "</span>&gt;</span></div><div class="line">    and bed_num=#&#123;bedNum&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="choose、when、otherwise"><a href="#choose、when、otherwise" class="headerlink" title="choose、when、otherwise"></a>choose、when、otherwise</h3><ul>
<li>有时候，我们不想使用所有的条件，而只是想从多个条件中选择一个使用。针对这种情况，MyBatis 提供了 <code>choose</code> 元素，它有点像 Java 中的 <code>switch</code> 语句。</li>
<li><p>还是上面的例子改变一下：此时只能满足一个筛选条件，如果前端传来住院号就只按照住院号查找，如果传来床位号就只按照床位号筛选，如果什么都没传，就筛选所有在院的。此时的查询如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectPats"</span></span></div><div class="line">     <span class="attr">resultType</span>=<span class="string">"com.xxx.domain.PatientInfo"</span>&gt;</div><div class="line">  select * from patient_info where 1=1</div><div class="line">  <span class="tag">&lt;<span class="name">choose</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!--住院号不为null时，根据住院号查找--&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">"iptNum != null"</span>&gt;</span></div><div class="line">      AND ipt_num=#&#123;iptNum&#125;</div><div class="line">    <span class="tag">&lt;/<span class="name">when</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!--床位号不是NUll--&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">"bedNum != null"</span>&gt;</span></div><div class="line">      AND bed_num = #&#123;bedNum&#125;</div><div class="line">    <span class="tag">&lt;/<span class="name">when</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">otherwise</span>&gt;</span></div><div class="line">      AND status=1</div><div class="line">    <span class="tag">&lt;/<span class="name">otherwise</span>&gt;</span></div><div class="line">  <span class="tag">&lt;/<span class="name">choose</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>MyBatis 提供了 <code>choose</code> 元素，按顺序判断 <code>when</code> 中的条件出否成立，如果有一个成立，则 <code>choose</code> 结束。当 <code>choose</code> 中所有 <code>when</code> 的条件都不满则时，则执行 <code>otherwise</code> 中的 sql。类似于 Java 的 <code>switch</code> 语句，<code>choose</code> 为 <code>switch</code>，<code>when</code> 为 <code>case</code>，<code>otherwise</code> 则为<code>default</code>。</p>
</li>
</ul>
<h3 id="where"><a href="#where" class="headerlink" title="where"></a>where</h3><ul>
<li><p>举个栗子：对于<code>choose</code>标签的例子中的查询，如果去掉<code>where</code>后的<code>1=1</code>此时的SQL语句会变成什么样子，有三种可能的SQL，如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">select</span> * <span class="keyword">from</span> patient_info <span class="keyword">where</span> <span class="keyword">AND</span> ipt_num=#&#123;iptNum&#125;;</div><div class="line"></div><div class="line"><span class="keyword">select</span> * <span class="keyword">from</span> patient_info <span class="keyword">where</span> <span class="keyword">AND</span> bed_num = #&#123;bedNum&#125;;</div><div class="line"></div><div class="line"><span class="keyword">select</span> * <span class="keyword">from</span> patient_info <span class="keyword">where</span> <span class="keyword">AND</span> <span class="keyword">status</span>=<span class="number">1</span>;</div></pre></td></tr></table></figure>
</li>
<li><p>发生了什么，以上三条SQL语句对吗？很显然是不对的，显然<code>where</code>后面多了个<code>AND</code>。如何解决呢？此时就要用到<code>where</code>这个标签了。</p>
</li>
<li><code>where</code> 元素只会在子元素返回任何内容的情况下才插入 <code>WHERE</code> 子句。而且，若子句的开头为 <code>AND</code> 或 <code>OR</code>，<code>where</code> 元素也会将它们去除。</li>
<li>此时的查询改造如下：<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectPats"</span></span></div><div class="line">     <span class="attr">resultType</span>=<span class="string">"com.xxx.domain.PatientInfo"</span>&gt;</div><div class="line">  select * from patient_info</div><div class="line">    <span class="tag">&lt;<span class="name">where</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">choose</span>&gt;</span></div><div class="line">          <span class="comment">&lt;!--住院号不为null时，根据住院号查找--&gt;</span></div><div class="line">          <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">"iptNum != null"</span>&gt;</span></div><div class="line">            AND ipt_num=#&#123;iptNum&#125;</div><div class="line">          <span class="tag">&lt;/<span class="name">when</span>&gt;</span></div><div class="line">          <span class="comment">&lt;!--床位号不是NUll--&gt;</span></div><div class="line">          <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">"bedNum != null"</span>&gt;</span></div><div class="line">            AND bed_num = #&#123;bedNum&#125;</div><div class="line">          <span class="tag">&lt;/<span class="name">when</span>&gt;</span></div><div class="line">          <span class="tag">&lt;<span class="name">otherwise</span>&gt;</span></div><div class="line">            AND status=1</div><div class="line">          <span class="tag">&lt;/<span class="name">otherwise</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">choose</span>&gt;</span></div><div class="line">   <span class="tag">&lt;/<span class="name">where</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="foreach"><a href="#foreach" class="headerlink" title="foreach"></a>foreach</h3><ul>
<li><code>foreach</code>是用来对集合的遍历，这个和Java中的功能很类似。通常处理SQL中的<code>in</code>语句。</li>
<li><code>foreach</code> 元素的功能非常强大，它允许你指定一个集合，声明可以在元素体内使用的集合项（<code>item</code>）和索引（<code>index</code>）变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符</li>
<li>你可以将任何可迭代对象（如 <code>List</code>、<code>Set</code> 等）、<code>Map</code> 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时，<code>index</code> 是当前迭代的序号，<code>item</code> 的值是本次迭代获取到的元素。当使用 <code>Map</code> 对象（或者 <code>Map.Entry</code> 对象的集合）时，<code>index</code> 是键，<code>item</code> 是值。</li>
<li><p>例子如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectPats"</span> <span class="attr">resultType</span>=<span class="string">"com.xxx.domain.PatientInfo"</span>&gt;</span></div><div class="line">  SELECT *</div><div class="line">  FROM patient_info </div><div class="line">  WHERE ID in</div><div class="line">  <span class="tag">&lt;<span class="name">foreach</span> <span class="attr">item</span>=<span class="string">"item"</span> <span class="attr">index</span>=<span class="string">"index"</span> <span class="attr">collection</span>=<span class="string">"list"</span></span></div><div class="line">      <span class="attr">open</span>=<span class="string">"("</span> <span class="attr">separator</span>=<span class="string">","</span> <span class="attr">close</span>=<span class="string">")"</span>&gt;</div><div class="line">        #&#123;item&#125;</div><div class="line">  <span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>改标签中的各个属性的含义如下：</p>
</li>
</ul>
<table>
<thead>
<tr>
<th>属性</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>item</td>
<td>表示在迭代过程中每一个元素的别名</td>
</tr>
<tr>
<td>index</td>
<td>表示在迭代过程中每次迭代到的位置（下标）</td>
</tr>
<tr>
<td>open</td>
<td>前缀</td>
</tr>
<tr>
<td>close</td>
<td>后缀</td>
</tr>
<tr>
<td>separator</td>
<td>分隔符，表示迭代时每个元素之间以什么分隔</td>
</tr>
</tbody>
</table>
<h3 id="set"><a href="#set" class="headerlink" title="set"></a>set</h3><ul>
<li><p>讲这个标签之前，先看下面这个例子：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateStudent"</span> <span class="attr">parameterType</span>=<span class="string">"Object"</span>&gt;</span></div><div class="line">    UPDATE STUDENT</div><div class="line">    SET NAME = #&#123;name&#125;,</div><div class="line">    MAJOR = #&#123;major&#125;,</div><div class="line">    HOBBY = #&#123;hobby&#125;</div><div class="line">    WHERE ID = #&#123;id&#125;;</div><div class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateStudent"</span> <span class="attr">parameterType</span>=<span class="string">"Object"</span>&gt;</span></div><div class="line">    UPDATE STUDENT SET</div><div class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"name!=null and name!='' "</span>&gt;</span></div><div class="line">        NAME = #&#123;name&#125;,</div><div class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"hobby!=null and hobby!='' "</span>&gt;</span></div><div class="line">        MAJOR = #&#123;major&#125;,</div><div class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"hobby!=null and hobby!='' "</span>&gt;</span></div><div class="line">        HOBBY = #&#123;hobby&#125;</div><div class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">    WHERE ID = #&#123;id&#125;;</div><div class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>上面的例子中没有使用 <code>if</code> 标签时，如果有一个参数为 <code>null</code>，都会导致错误。当在 <code>update</code> 语句中使用 <code>if</code> 标签时，如果最后的 <code>if</code> 没有执行，则或导致逗号多余错误。使用 <code>set</code> 标签可以将动态的配置 <code>set</code> 关键字，和剔除追加到条件末尾的任何不相关的逗号。</p>
</li>
<li><p>使用 set+if 标签修改后，如果某项为 null 则不进行更新，而是保持数据库原值。此时的查询如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateStudent"</span> <span class="attr">parameterType</span>=<span class="string">"Object"</span>&gt;</span></div><div class="line">    UPDATE STUDENT</div><div class="line">    <span class="tag">&lt;<span class="name">set</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"name!=null and name!='' "</span>&gt;</span></div><div class="line">            NAME = #&#123;name&#125;,</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"hobby!=null and hobby!='' "</span>&gt;</span></div><div class="line">            MAJOR = #&#123;major&#125;,</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"hobby!=null and hobby!='' "</span>&gt;</span></div><div class="line">            HOBBY = #&#123;hobby&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">set</span>&gt;</span></div><div class="line">    WHERE ID = #&#123;id&#125;;</div><div class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="sql"><a href="#sql" class="headerlink" title="sql"></a>sql</h3><ul>
<li>在实际开发中会遇到许多相同的SQL，比如根据某个条件筛选，这个筛选很多地方都能用到，我们可以将其抽取出来成为一个公用的部分，这样修改也方便，一旦出现了错误，只需要改这一处便能处处生效了，此时就用到了<code>&lt;sql&gt;</code>这个标签了。</li>
<li>当多种类型的查询语句的查询字段或者查询条件相同时，可以将其定义为常量，方便调用。为求 <code>&lt;select&gt;</code> 结构清晰也可将 sql 语句分解。如下：<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 查询字段 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">"Base_Column_List"</span>&gt;</span></div><div class="line">    ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY</div><div class="line"><span class="tag">&lt;/<span class="name">sql</span>&gt;</span></div><div class="line"></div><div class="line"><span class="comment">&lt;!-- 查询条件 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">"Example_Where_Clause"</span>&gt;</span></div><div class="line">    where 1=1</div><div class="line">    <span class="tag">&lt;<span class="name">trim</span> <span class="attr">suffixOverrides</span>=<span class="string">","</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"id != null and id !=''"</span>&gt;</span></div><div class="line">            and id = #&#123;id&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"major != null and major != ''"</span>&gt;</span></div><div class="line">            and MAJOR = #&#123;major&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"birthday != null "</span>&gt;</span></div><div class="line">            and BIRTHDAY = #&#123;birthday&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"age != null "</span>&gt;</span></div><div class="line">            and AGE = #&#123;age&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"name != null and name != ''"</span>&gt;</span></div><div class="line">            and NAME = #&#123;name&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"hobby != null and hobby != ''"</span>&gt;</span></div><div class="line">            and HOBBY = #&#123;hobby&#125;</div><div class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">trim</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">sql</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="include"><a href="#include" class="headerlink" title="include"></a>include</h3><ul>
<li><p>这个标签和<code>&lt;sql&gt;</code>是天仙配，是共生的，<code>include</code>用于引用<code>sql</code>标签定义的常量。比如引用上面sql标签定义的常量，如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectAll"</span> <span class="attr">resultMap</span>=<span class="string">"BaseResultMap"</span>&gt;</span></div><div class="line">    SELECT</div><div class="line">    <span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">"Base_Column_List"</span> /&gt;</span></div><div class="line">    FROM student</div><div class="line">    <span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">"Example_Where_Clause"</span> /&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p><code>refid</code>这个属性就是指定<code>&lt;sql&gt;</code>标签中的<code>id</code>值（唯一标识）。</p>
</li>
</ul>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ul>
<li>至此，Mybatis动态SQL中常用的标签就已经介绍完了，这部分的内容在实际工作中是必须会用到的，除非你们公司不用Mybatis。</li>
</ul>
<h2 id="拓展一下"><a href="#拓展一下" class="headerlink" title="拓展一下"></a>拓展一下</h2><ul>
<li>前面介绍了动态SQL的一些标签以及属性，相信看完之后应该能够灵活的应用了，但是在实际开发中还是有一些奇技淫巧的，陈某今天简单的讲几个。</li>
</ul>
<h3 id="Mybatis中如何避免魔数"><a href="#Mybatis中如何避免魔数" class="headerlink" title="Mybatis中如何避免魔数"></a>Mybatis中如何避免魔数</h3><ul>
<li>开过阿里巴巴开发手册的大概都知道代码中是不允许出现<code>魔数</code>的，何为<code>魔数</code>？简单的说就是一个数字，一个只有你知道，别人不知道这个代表什么意思的数字。通常我们在Java代码中都会定义一个常量类专门定义这些数字。</li>
<li><p>比如获取医生和护士的权限，但是医生和护士的权限都不相同，在这条SQL中肯定需要根据登录的类型<code>type</code>来区分，比如<code>type=1</code>是医生，<code>type=2</code>是护士，估计一般人会这样写：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"type!=null and type==1"</span>&gt;</span></div><div class="line">    -- ....获取医生的权限</div><div class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"type!=null and type==2"</span>&gt;</span></div><div class="line">    -- ....获取护士的权限</div><div class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>这样写也没什么错，但是一旦这个<code>type</code>代表的含义变了，那你是不是涉及到的SQL都要改一遍。</p>
</li>
<li><p>开发中通常定义一个常量类，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> com.xxx.core.Constants;</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommonConstants</span></span>&#123;</div><div class="line">  <span class="comment">//医生</span></div><div class="line">  <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">int</span> DOC_TYPE=<span class="number">1</span>;</div><div class="line">  </div><div class="line">  <span class="comment">//护士</span></div><div class="line">  <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">int</span> NUR_TYPE=<span class="number">2</span>;</div><div class="line">  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>那么此时的SQL应该如何写呢？如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"type!=null and type==@com.xxx.core.Constants.CommonConstants@DOC_TYPE"</span>&gt;</span></div><div class="line">    -- ....获取医生的权限</div><div class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"type!=null and type==@com.xxx.core.Constants.CommonConstants@NUR_TYPE"</span>&gt;</span></div><div class="line">    -- ....获取护士的权限</div><div class="line"><span class="tag">&lt;/<span class="name">if</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>就是这么简单，就是<code>@</code>+<code>全类名</code>+<code>@</code>+<code>常量</code>。</p>
</li>
<li>除了调用常量类中的常量，还可以类中的方法，很少用到，不再介绍了，感兴趣的可以问下度娘。</li>
</ul>
<h3 id="如何引用其他XML中的SQL片段"><a href="#如何引用其他XML中的SQL片段" class="headerlink" title="如何引用其他XML中的SQL片段"></a>如何引用其他XML中的SQL片段</h3><ul>
<li>实际开发中你可能遇到一个问题，比如这个<code>resultMap</code>或者这个<code>&lt;sql&gt;</code>片段已经在另外一个<code>xxxMapper.xml</code>中已经定义过了，此时当前的xml还需要用到，难不成我复制一份？小白什么也不问上来就复制了，好吧，后期修改来了，每个地方都需要修改了。难受不？</li>
<li><p>其实Mybatis中也是支持引用其他Mapper文件中的SQL片段的。其实很简单，比如你在<code>com.xxx.dao.xxMapper</code>这个Mapper的XML中定义了一个SQL片段如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">"Base_Column_List"</span>&gt;</span></div><div class="line">    ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY</div><div class="line"><span class="tag">&lt;/<span class="name">sql</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>此时我在<code>com.xxx.dao.PatinetMapper</code>中的XML文件中需要引用，如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">"com.xxx.dao.xxMapper.Base_Column_List"</span>&gt;</span><span class="tag">&lt;/<span class="name">include</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>如此简单，类似于Java中的全类名。</p>
</li>
<li><code>&lt;select&gt;</code>标签中的<code>resultMap</code>同样可以这么引用，和上面引用的方式一样，不再赘述了。</li>
</ul>
<h2 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h2><ul>
<li>好了，Myabtis的动态SQL的内容已经介绍完了，你会了吗？每日来看看，下面会有更多精彩的内容！！！</li>
<li>如果 觉得写的不错的，点点在看，关注一波不迷路，每天都会有精彩内容分享。<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/%E4%B8%83%E7%A7%92%E7%BC%96%E7%A8%8B.jpg" alt=""></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>写的可还行？</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.jpg" alt="不才陈某 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
	<div>
	
<div>
      
        
      
</div>

  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mybatis/" rel="tag"><i class="fa fa-tag"></i> Mybatis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/20/Mybatis入门之结果映射/" rel="next" title="Mybatis入门之结果映射">
                <i class="fa fa-chevron-left"></i> Mybatis入门之结果映射
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/20/Mybatis的几种传参方式，你了解吗？/" rel="prev" title="Mybatis的几种传参方式，你了解吗？">
                Mybatis的几种传参方式，你了解吗？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="不才陈某" />
            
              <p class="site-author-name" itemprop="name">不才陈某</p>
              <p class="site-description motion-element" itemprop="description">本站是不才陈某的技术分享博客。内容涵盖Java后端技术、Spring Boot、微服务架构、系统安全、前端、系统监控等相关的研究与知识分享。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">63</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/1556564194374926" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-globe"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/xiao-ming-64-34-45" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_34162294" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png" target="_blank" title="微信公众号">
                      
                        <i class="fa fa-fw fa-globe"></i>微信公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.pexels.com/zh-cn/" title="Pexels" target="_blank">Pexels</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/" title="纯洁的微笑" target="_blank">纯洁的微笑</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是动态SQL？"><span class="nav-text">什么是动态SQL？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常用的标签"><span class="nav-text">常用的标签</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#if"><span class="nav-text">if</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#choose、when、otherwise"><span class="nav-text">choose、when、otherwise</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#where"><span class="nav-text">where</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#foreach"><span class="nav-text">foreach</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#set"><span class="nav-text">set</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sql"><span class="nav-text">sql</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#include"><span class="nav-text">include</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拓展一下"><span class="nav-text">拓展一下</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Mybatis中如何避免魔数"><span class="nav-text">Mybatis中如何避免魔数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何引用其他XML中的SQL片段"><span class="nav-text">如何引用其他XML中的SQL片段</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结-1"><span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">不才陈某</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">143.1k</span>
  
</div>

<!--





  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共143.1k字</span>
</div>

        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'RtlQOgOT3M0hgyMeogykSQjT-gzGzoHsz',
        appKey: 'vSCxLU88wnXVf0Pa8mwJrCPm',
        placeholder: '原创不易，欢迎各位指正',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
